<script setup lang="tsx">
import type { Ref } from 'vue';
import { ref } from 'vue';
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import { $t } from '@/locales';
import { fetchDelRole, fetchGetRoleList } from '@/service/api';
import { useAppStore } from '@/store/modules/app';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { enableStatusRecord } from '@/constants/business';
import RoleOperateModal from '@/views/manage/role/modules/role-operate-modal.vue';
import RoleSearch from '@/views/manage/role/modules/role-search.vue';
import { useAuth } from '@/hooks/business/auth';
import MenuAuthModal from '@/views/manage/role/modules/menu-auth-modal.vue';
import { useBoolean } from '~/packages/hooks';
import ButtonAuthModal from '@/views/manage/role/modules/button-auth-modal.vue';

const appStore = useAppStore();
const wrapperRef = ref<HTMLElement | null>(null);

const { hasAuth } = useAuth();
const {
  columns,
  data,
  loading,
  mobilePagination,
  getData,
  getDataByPage,
  resetSearchParams,
  searchParams,
  columnChecks
} = useTable({
  apiFn: fetchGetRoleList,
  apiParams: {
    current: 1,
    size: 10,
    name: null,
    code: null,
    status: null
  },
  columns: () => [
    {
      key: 'id',
      title: $t('common.index'),
      width: 48,
      align: 'center'
    },
    {
      key: 'name',
      title: $t('page.manage.role.roleName'),
      align: 'center',
      minWidth: 100
    },
    {
      key: 'code',
      title: $t('page.manage.role.roleCode'),
      align: 'center',
      minWidth: 100
    },
    {
      key: 'level',
      title: $t('page.manage.role.roleLevel'),
      align: 'center',
      minWidth: 80
    },
    {
      key: 'status',
      title: $t('page.manage.role.roleStatus'),
      align: 'center',
      minWidth: 80,
      render: row => {
        if (row.status === null) {
          return null;
        }

        const tagMap: Record<Api.Common.EnableStatus, NaiveUI.ThemeColor> = {
          1: 'success',
          2: 'warning'
        };

        const label = $t(enableStatusRecord[row.status]);

        return <NTag type={tagMap[row.status]}>{label}</NTag>;
      }
    },
    {
      key: 'description',
      title: $t('page.manage.role.roleDesc'),
      minWidth: 100
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      minWidth: 230,
      render: row => {
        return (
          <div class="flex-center justify-end gap-8px">
            {hasAuth('sys:role:auth') && (
              <NButton type="primary" ghost size="small" onClick={() => handleMenuAuth(row.id)}>
                {$t('page.manage.role.menuAuth')}
              </NButton>
            )}
            {hasAuth('sys:role:auth') && (
              <NButton type="primary" ghost size="small" onClick={() => handleButtonAuth(row.id)}>
                {$t('page.manage.role.buttonAuth')}
              </NButton>
            )}
            {hasAuth('sys:role:edit') && (
              <NButton type="primary" ghost size="small" onClick={() => edit(row.id)}>
                {$t('common.edit')}
              </NButton>
            )}
            {hasAuth('sys:role:delete') && (
              <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
                {{
                  default: () => $t('common.confirmDelete'),
                  trigger: () => (
                    <NButton type="error" ghost size="small">
                      {$t('common.delete')}
                    </NButton>
                  )
                }}
              </NPopconfirm>
            )}
          </div>
        );
      }
    }
  ]
});

const { drawerVisible, operateType, editingData, handleAdd, handleEdit, onDeleted } = useTableOperate(data, getData);

const { bool: menuModalVisible, setTrue: openMenuModal } = useBoolean();
const { bool: buttonModalVisible, setTrue: openButtonModal } = useBoolean();
const roleId: Ref<string> = ref('0');
function edit(id: number) {
  handleEdit(id);
}
function handleMenuAuth(id: number) {
  roleId.value = String(id);
  openMenuModal();
}
function handleButtonAuth(id: number) {
  roleId.value = String(id);
  openButtonModal();
}
async function handleDelete(id: number) {
  const { error, data: result } = await fetchDelRole(id);
  if (!error && result) {
    onDeleted();
  }
}
</script>

<template>
  <div ref="wrapperRef" class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <RoleSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage" />
    <NCard :title="$t('page.manage.role.title')" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :loading="loading"
          add-auth="sys:role:add"
          @refresh="getData"
          @add="handleAdd"
        />
      </template>
      <NDataTable
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="1088"
        :loading="loading"
        :row-key="row => row.id"
        remote
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <RoleOperateModal
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getDataByPage"
      />
      <MenuAuthModal v-model:visible="menuModalVisible" :role-id="roleId" />
      <ButtonAuthModal v-model:visible="buttonModalVisible" :role-id="roleId" />
    </NCard>
  </div>
</template>

<style scoped></style>
